package com.jbm;

import org.apache.mina.core.service.IoHandlerAdapter;
import org.apache.mina.core.session.IoSession;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.net.InetSocketAddress;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;

/**
 * Created by root on 18-6-11.
 */
public class GDHandler extends IoHandlerAdapter
{
	protected static Logger logger = LoggerFactory.getLogger(GDHandler.class);

	public static Resource gd_pool = new Resource(200,"gd_ppol");
	public static BlockingQueue db_pool = null;

	@Override
	public void exceptionCaught(IoSession session, Throwable cause)
			throws Exception
	{
		cause.printStackTrace();
	}

	@Override
	public void messageReceived(IoSession session, Object message)
			throws Exception
	{
		byte[] msg = (byte[])message;

		if ( msg[8] == 0x49 && msg[9] == 0x43 )
		{
			byte[] response = {0x01, 0x30, 0x30, 0x30, 0x30, 0x30, 0x30, 0x30, 0x49, 0x43, 0x02, 0x43, 0x36, 0x34, 0x38, 0x0D};
			session.write(response);
		}

		ConnectAgent ca = (ConnectAgent)session.getAttribute("CA_Key");

		ca.IamLiving();
	}

	@Override
	public void sessionCreated(IoSession session) throws Exception
	{
		ConnectAgent ca = new ConnectAgent(0,((InetSocketAddress)session.getRemoteAddress()).getAddress().getHostAddress(),
				((InetSocketAddress)session.getRemoteAddress()).getPort(),
				((InetSocketAddress)session.getLocalAddress()).getPort(),
				ConnectAgent.CA_Type_GD_Server,40000);
		ca.Born(3,40000);
		ca.setM_iosession(session);

		gd_pool.Add(ca);

		session.setAttribute("CA_Key",ca);

		if ( db_pool != null )
		{
			Connection conn = (Connection) db_pool.take();
			Statement stmt = conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE);

			String sql = "update entrance_guard set online_status = 'online' where " +
					"equard_code = '" + ca.m_remotehost + "'";

			stmt.executeUpdate(sql);

			stmt.close();

			db_pool.add(conn);
		}

		logger.info("客户端与服务端创建连接...port:" + ((InetSocketAddress) session.getRemoteAddress()).getPort());
	}

	@Override
	public void sessionClosed(IoSession session) throws Exception {
		ConnectAgent ca = (ConnectAgent)session.getAttribute("CA_Key");
		if ( ca != null )
			ca.Die();

		if ( db_pool != null )
		{
			Connection conn = (Connection) db_pool.take();
			Statement stmt = conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE);

			String sql = "update entrance_guard set online_status = 'offline' where " +
					"equard_code = '" + ca.m_remotehost + "'";

			stmt.executeUpdate(sql);

			stmt.close();

			db_pool.add(conn);
		}
	}
}
